<template>
  <div>
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="4">
        <p style="font-weight: 800; font-size: 16px; margin: 0; padding: 0;">系统用户列表</p>
        <p style="font-size: 12px; color: #666; margin: 0; padding: 0;">共 {{ totalUsers }} 人</p>
      </el-col>
      <el-col :span="12">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input v-model="searchUnit" placeholder="请输入工作单位进行搜索" size="small" class="custom-input">
              <template slot="suffix">
                <i class="el-icon-search custom-icon"></i>
              </template>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-input v-model="searchAccount" placeholder="请输入账号" size="small" class="custom-input">
              <template slot="suffix">
                <i class="el-icon-search custom-icon"></i>
              </template>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-input v-model="searchName" placeholder="请输入姓名进行搜索" size="small" class="custom-input">
              <template slot="suffix">
                <i class="el-icon-search custom-icon"></i>
              </template>
            </el-input>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="8" style="text-align: right;">
        <el-button type="primary" @click="handleAddUser">+添加系统用户</el-button>
        <el-button type="danger" @click="handleBulkDisable">批量停用</el-button>
        <el-button type="success" @click="handleBulkEnable">批量启用</el-button>
      </el-col>
    </el-row>

    <!-- 用户列表 -->
    <el-table :data="filteredUsers" style="width: 100%">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="hospName" label="工作单位" width="180"></el-table-column>
      <el-table-column prop="userName" label="账号" width="180"></el-table-column>
      <el-table-column prop="nickName" label="姓名" width="180"></el-table-column>
      <el-table-column prop="department" label="科室" width="180"></el-table-column>
      <el-table-column label="角色" width="320" prop="roleName">
        <!--        <template slot-scope="scope">-->
        <!--          <el-tag v-for="roleName in scope.row.roleNames" :key="roleName">{{ roleName }}</el-tag>-->
        <!--        </template>-->
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.row)" type="primary" size="mini">编辑</el-button>
          <el-button @click="handleToggleStatus(scope.row)" :type="scope.row.status === '0' ? 'danger' : 'success'"
            size="mini">
            {{ scope.row.status === '0' ? '停用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增用户对话框 -->
    <el-dialog title="新增用户" :visible.sync="showAddDialog" width="500px">
      <el-form :model="newUser" label-width="100px" size="small" ref="userForm">
        <el-form-item label="账号" required>
          <el-input v-model="newUser.userName" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" required>
          <el-input v-model="newUser.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="工作单位" required>
          <el-select v-model="newUser.hospId" placeholder="请选择工作单位">
            <el-option label="云南省第一人民医院" value="1"></el-option>
            <el-option label="玉溪市人民医院" value="2"></el-option>
            <el-option label="普洱市人民医院" value="3"></el-option>
            <el-option label="镇雄县人民医院" value="4"></el-option>
            <el-option label="保山市人民医院" value="5"></el-option>
            <el-option label="个旧市人民医院" value="6"></el-option>
            <el-option label="西双版纳州人民医院" value="7"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" required>
          <el-input v-model="newUser.nickName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="科室" required>
          <el-input v-model="newUser.department" placeholder="请输入科室"></el-input>
        </el-form-item>
        <el-form-item label="角色" required>
          <el-checkbox-group v-model="newUser.roleIds">
            <el-checkbox v-for="item in roleOptions" :label="item.roleId" :key="item.roleId">{{ item.roleName
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAddUser">确定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="showEditDialog" width="500px">
      <el-form :model="editUser" label-width="100px" size="small" ref="editUserForm">
        <el-form-item label="账号" required>
          <el-input v-model="editUser.userName" placeholder="请输入账号" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" required>
          <el-input v-model="editUser.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="工作单位" required>
          <el-select v-model="editUser.hospId" placeholder="请选择工作单位">
            <el-option label="云南省第一人民医院" value="1"></el-option>
            <el-option label="玉溪市人民医院" value="2"></el-option>
            <el-option label="普洱市人民医院" value="3"></el-option>
            <el-option label="镇雄县人民医院" value="4"></el-option>
            <el-option label="保山市人民医院" value="5"></el-option>
            <el-option label="个旧市人民医院" value="6"></el-option>
            <el-option label="西双版纳州人民医院" value="7"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" required>
          <el-input v-model="editUser.nickName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="科室" required>
          <el-input v-model="editUser.department" placeholder="请输入科室"></el-input>
        </el-form-item>
        <el-form-item label="角色" required>
          <el-checkbox-group v-model="editUser.roleIds">
            <el-checkbox v-for="item in roleOptions" :label="item.roleId" :key="item.roleId">{{ item.roleName
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmEditUser">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listRole } from "@/api/system/role";
import { listUserNew, changeStatus, addUser, updateUser } from "@/api/system/user";

export default {
  data() {
    return {
      totalUsers: 0, // 用户总数
      searchUnit: '', // 搜索框-工作单位
      searchName: '', // 搜索框-姓名
      searchAccount: '', // 搜索框-账号
      users: [], // 用户列表数据
      showAddDialog: false, // 控制新增用户对话框的显示
      showEditDialog: false, // 控制编辑用户对话框的显示
      newUser: {
        userName: '', // 新增用户的账号
        password: '', // 新增用户的密码
        nickName: '', // 新增用户的姓名
        hospId: '', // 新增用户的工作单位
        department: '', // 新增用户的科室
        roleIds: [], // 新增用户的角色ID数组
      },
      editUser: {
        userId: null, // 编辑用户的ID
        userName: '', // 编辑用户的账号
        password: '', // 编辑用户的密码
        nickName: '', // 编辑用户的姓名
        hospId: '', // 编辑用户的工作单位
        department: '', // 编辑用户的科室
        roleIds: [], // 编辑用户的角色ID数组
      },
      roleOptions: [], // 角色选项列表
      rolesMap: {}, // 角色ID到角色名称的映射
      queryParams: {} // 查询参数
    }
  },
  created() {
    this.getList(); // 获取用户列表
    this.getRoleOptions(); // 获取角色选项
  },
  computed: {
    // 过滤用户列表，基于搜索条件
    filteredUsers() {
      return this.users.filter(user => {
        return (
          (user.hospName && user.hospName.includes(this.searchUnit)) &&
          (user.nickName && user.nickName.includes(this.searchName)) &&
          (user.userName && user.userName.includes(this.searchAccount))
        )
      })
    }
  },
  methods: {
    // 获取用户列表
    async getList() {
      try {
        const res = await listUserNew(this.queryParams);
        const users = res.rows;

        for (const user of users) {
          if (!Array.isArray(user.roleIds)) {
            user.roleIds = [];
          }

          // 获取用户的角色名称
          // user.roleNames = user.roleIds.map(roleId => this.rolesMap[roleId] || '未知角色');
          // console.log(`User ID: ${user.userId}, Role Names: ${user.roleId}`);
        }

        this.users = users;
        this.totalUsers = users.length; // 更新用户总数
        this.newUser = { userName: '', password: '', nickName: '', hospId: '', department: '', roleIds: [] };
      } catch (error) {
        console.error('Error fetching user list:', error);
      }
    },
    // 获取角色选项
    async getRoleOptions() {
      try {
        const response = await listRole({});
        this.roleOptions = response.rows.map(role => {
          return {
            roleId: role.roleId,
            roleName: role.roleName
          };
        });

        // 创建角色ID到角色名称的映射
        this.rolesMap = this.roleOptions.reduce((map, role) => {
          map[role.roleId] = role.roleName;
          return map;
        }, {});
      } catch (error) {
        console.error('Error fetching role options:', error);
      }
    },
    // 显示新增用户对话框
    handleAddUser() {
      this.showAddDialog = true;
    },
    // 确认新增用户
    confirmAddUser() {
      addUser(this.newUser).then(res => {
        this.showAddDialog = false;
        this.getList();
      })
    },
    // 显示编辑用户对话框
    handleEdit(user) {
      this.editUser = { ...user, userId: user.userId }; // 确保设置 userId
      this.showEditDialog = true;
    },
    // 确认编辑用户
    confirmEditUser() {
      updateUser(this.editUser).then(res => {
        this.showEditDialog = false;
        this.getList();
      })
    },
    // 切换用户状态
    handleToggleStatus(user) {
      user.status = user.status === '0' ? '1' : '0';
      changeStatus(user.userId, user.status).then(res => {
        this.getList();
      })
    },
    // 批量停用用户
    handleBulkDisable() {
      this.users.forEach(user => {
        user.status = '1';
        changeStatus(user.userId, user.status).then(res => {
          this.getList();
        })
      });
    },
    // 批量启用用户
    handleBulkEnable() {
      this.users.forEach(user => {
        user.status = '0';
        changeStatus(user.userId, user.status).then(res => {
          this.getList();
        })
      });
    }
  }
}
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}

.custom-input .el-input__inner {
  padding-right: 30px;
}

.custom-input .el-input__suffix {
  right: 10px;
}

.custom-icon {
  font-size: 16px;
  line-height: 1;
  height: 100%;
  display: flex;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}</style>
